import java.util.Scanner;
import edu.purdue.cs.cs180.channel.*;

/**
 * project6
 *
 * brief description of the program
 *
 * This program is released to public domain according to
 * author's wish, you can view full license at
 * http://tomatoeskit.org/upload/PublicDomainLicense.txt
 *
 * @author Fangning CHENG (Alpha.L Cheng) <chengf@purdue.edu>
 *
 * @lab section number 
 *
 * @date Oct 25, 2013
 *
 */

public class Volunteer implements MessageListener {

    Channel channel;
    Scanner scanner = new Scanner(System.in);
    
    Volunteer(Channel cnl)
    {
        channel = cnl;
        channel.setMessageListener(this);
        processPrompt();
    }
       
    @Override
    public void messageReceived(String message, int clientID) {
        String msg[] = message.split("\\s+");
        if (msg.length < 2)
            return;
        if (msg[0].equals("LOCATION")) {
            System.out.println(String.format("Proceed to %s", msg[1])); 
            processPrompt();
        }        
    }

    private void processPrompt()
    {
        System.out.println("Press ENTER when ready:");
        scanner.nextLine();
        sendMessage();
    }
    
    public void sendMessage()
    {
        try {
            channel.sendMessage("VOLUNTEER " + channel.getID());
            System.out.println("Waiting for assignment...");
        } catch (ChannelException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
    
    
    public static void main(String[] args) {
        int argsLen = args.length;
        String srvAddr;
        int srvPort;
        if (argsLen < 2) {
            System.out.println("Invalid arguments");
            return;
        }
        try {
            srvPort = Integer.parseInt(args[1]);
            if (srvPort < 1024 || srvPort > 65535)
                throw new Exception();
        } catch (Exception ex) {
            System.out.println("Invalid port");
            return;
        }
        srvAddr = args[0];
        @SuppressWarnings("unused")
        Volunteer volunteer;

        try {
            volunteer = new Volunteer(new TCPChannel(srvAddr, srvPort));
        } catch (ChannelException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }     
    }   
}
